import '@/page/Board/index.scss'
import { Tooltip, Popconfirm, message } from 'antd'
import { useState, useRef, useEffect } from 'react'
import Shape from '@/component/Shape'
import Line from '@/component/Line'
import Pens from '@/component/Pens'
import Text from '@/component/Text'
import Canvas from '@/component/Canvas'
import { useNavigate } from 'react-router-dom'
// import { useUserInfo } from '@/context/userInfoContext' // 不再需要
import '@/component/Canvas/index.scss'
import '@/component/Shape/index.scss'
import '@/component/Line/index.scss'
import '@/component/Pens/index.scss'
import '@/component/Text/index.scss'
import { uploadImageService, saveImageService } from '@/api/image'

function Board() {
  const navigate = useNavigate()
  const canvasRef = useRef(null)
  // const { userInfo } = useUserInfo() // 不再需要，用户ID从后端认证中间件获取
  
  // 画布变化状态
  const [canvasChanged, setCanvasChanged] = useState(false)
  
  const handleSave = async () => {
    // 前置校验：画布未准备好直接返回    
    if (!canvasRef.current) {
      message.error('画布未准备好，请稍后重试');
      return; // 提前退出，减少嵌套
    }
    
    // 检查画布是否有变化
    if (!canvasChanged) {
      message.warning('画布没有新的变化，无需保存');
      return;
    }
    
    try {
      // 检查画布是否有内容
      const canvas = canvasRef.current
      const ctx = canvas.getContext('2d')
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      const hasContent = imageData.data.some(pixel => pixel !== 0)
      console.log('画布是否有内容:', hasContent)
      
      if (!hasContent) {
        message.warning('画布为空，没有内容可保存');
        return;
      }
      
      // 从canvas获取DataURL并上传，此时为base64格式
      const dataUrl = canvasRef.current.toDataURL('image/png')
      console.log('dataUrl', dataUrl)
      // 将base64格式转换为blob二进制格式
      const blob = await fetch(dataUrl).then(res => res.blob())
      console.log('Blob size:', blob.size)
      console.log('是否为 Blob 对象:', blob instanceof Blob)
      
      // 创建FormData（字段名与后端uploadCanvas.single('canvasImage')一致）
      const formData = new FormData()
      formData.append('canvasImage', blob, 'canvas-drawing.png')
      // 检查formData内容是否正确
      for (const [key, value] of formData.entries()) {
        console.log('FormData 字段名:', key); // 必须和后端一致："canvasImage"
        console.log('FormData 字段值类型:', value.constructor.name); // 必须是 "Blob"
        console.log('FormData 文件名:', value.name); // 应为 "canvas-drawing.png"
      }
      console.log('FormData 条目数:', formData.entries().next().done ? 0 : 1); // 应为 1

      message.info('上传中...')
    
      // 调用后端接口，上传图片，获取图片访问路径
      const uploadRes = await uploadImageService(formData)
      console.log('上传图片res', uploadRes)
      console.log('uploadRes.code:', uploadRes.code)
      console.log('uploadRes.data:', uploadRes.data)
      
      if (uploadRes.data.code === 200) {
        message.success('上传成功')
      } else {
        console.log('上传失败，响应数据:', uploadRes)
        return message.error('上传失败', uploadRes.data.message || '未知错误')
      }
      const imgUrl = uploadRes.data.data.imageUrl
      console.log('imgUrl', imgUrl)

      // 调用后端接口，保存图片
      const saveRes = await saveImageService(imgUrl)
      console.log('保存图片res', saveRes)
      if (saveRes.data.code === 200) {
        message.success('保存成功')
        // 保存成功后重置变化状态
        setCanvasChanged(false)
      } else {
        message.error('保存失败', saveRes.message)
      }
    } catch (error) {
      console.error('保存画布时出错:', error)
      message.error('保存失败，请重试')
    }
  }
  const handleCancel = () => {
    // 直接返回
    navigate(-1)
  }
  // 绘制模式
  const [drawMode, setDrawMode] = useState('')
  const [toolbarIsShow, setToolbarIsShow] = useState(true)
  const [penColor, setPenColor] = useState('')
  const toolbarList = [
    {
      id: 0,
      icon: '&#xe604;',
      title: '选择工具',
      color: ''
    },
    {
      id: 1,
      icon: '&#xe69a;',
      title: '容器',
      color: 'green'
    },
    {
      id: 2,
      icon: '&#xe600;',
      title: '形状与流程图',
      color: 'red'
    },
    {
      id: 3,
      icon: '&#xe67c;',
      title: '连接线',
      color: 'blue'
    },
    {
      id: 4,
      icon: '&#xe632;',
      title: '画笔',
      color: 'pink'
    },
    {
      id: 5,
      icon: '&#xe65c;',
      title: '文本',
      color: 'purple'
    }
  ]
  // 工具栏高亮id
  const [activeToolId, setActiveToolId] = useState(null)
  // 画笔栏高亮id
  const [activePenId, setActivePenId] = useState(null)
  
  // 选中的形状
  const [selectedShape, setSelectedShape] = useState(null)
  // 选中的连接线
  const [selectedLine, setSelectedLine] = useState(null)
  // 选中的文本框
  const [selectedText, setSelectedText] = useState(null)
  // 处理工具栏点击事件
  const handleToolClick = (id) => {
    setActiveToolId(id)
    switch (id) {
      case 0:
        setDrawMode('select')
        setSelectedShape(null) // 清除选中的形状
        setSelectedLine(null) // 清除选中的连接线
        setSelectedText(null) // 清除选中的文本框
        setActivePenId(null) // 清除选中的画笔
        break
      case 1:
        setDrawMode('container')
        break
      case 2:
        setDrawMode('shape')
        break
      case 3:
        setDrawMode('line')
        break
      case 4:
        setDrawMode('pen')
        break
      case 5:
        setDrawMode('text')
        break
    }
  }
  // 处理清屏
  const clearCanvasRef = useRef(null)
  const handleClear = () => {
    console.log('清屏')
    clearCanvasRef.current() // 调用canvas组件传来的的clearCanvas方法
  }
  // 处理撤销
  const undoRef = useRef(null)
  const handleUndo = () => {
    console.log('撤销')
    if(undoRef.current) {
      undoRef.current()
    }
  }
  // 处理重做
  const redoRef = useRef(null)
  const handleRedo = () => {
    console.log('重做')
    if(redoRef.current) {
      redoRef.current()
    }
  }
  
  // 处理形状选择
  const handleShapeSelect = (shape) => {
    setSelectedShape(shape)
    setDrawMode('shape')
    setSelectedLine(null) // 切换到形状模式时取消连接线选择
    setActivePenId(null)  // 切换到形状模式时取消画笔选择
    setSelectedText(null) // 切换到形状模式时取消文本框选择
  }

  // 处理连接线选择
  const handleLineSelect = (line) => {
    setSelectedLine(line)
    setDrawMode('line')
    setSelectedShape(null) 
    setActivePenId(null)
    setSelectedText(null)
  }

  // 处理文本框选择
  const handleTextSelect = (text) => {
    setSelectedText(text)
    setDrawMode('text')
    setSelectedShape(null)
    setSelectedLine(null)
    setActivePenId(null)
  }

  useEffect(() => {
    console.log('更新后的 selectedText:', selectedText);
  }, [selectedText])

  return (
    <div className="board-index">
      {/* 左上角工具栏 */}
      <div className="left-header">
        <div className="back-btn">
          <Popconfirm
            title="save"
            description="是否保存当前文件"
            onConfirm={handleSave}
            onCancel={handleCancel}
            okText="是"
            cancelText="否"
          >
            <i className="iconfont">&#xe6c8;</i>
          </Popconfirm>
        </div>
        <div className="save-btn" onClick={handleSave}>
          <Tooltip title="保存">
            <i className="iconfont">&#xe60a;</i>
          </Tooltip>
        </div>
        <div className="board-title">
          <span>未命名文件</span>
        </div>
        <div className="btn-container">
          <div className="undo" onClick={handleUndo}>
            <Tooltip title="撤销">
              <i className="iconfont">&#xe740;</i>
            </Tooltip>
          </div>
          <div className="redo" onClick={handleRedo}>
            <Tooltip title="重做">
              <i className="iconfont">&#xe75e;</i>
            </Tooltip>
          </div>
          <div className="clear" onClick={handleClear}>
            <Tooltip title="清屏">
              <i className="iconfont">&#xe7bb;</i>
            </Tooltip>
          </div>
        </div>
      </div>
      {/* 左侧工具栏 */}
      <div className={`left-toolbar ${!toolbarIsShow && 'left-toolbar-anim'}`}>
        <div className="left-toolbar-top">
          <Tooltip title={toolbarIsShow ? '收起画笔栏' : '展开画笔栏'} color='blue'>
            <i onClick={() => setToolbarIsShow(!toolbarIsShow)} className="iconfont">&#xe605;</i>
          </Tooltip>
        </div>
        {toolbarIsShow && <div className="left-toolbar-line"></div>}
        {toolbarIsShow &&
          <div className="left-toolbar-other">
            {toolbarList.map(item => (
              <div onClick={() => handleToolClick(item.id)}
                className={`icon-container ${activeToolId === item.id && 'active'}`}
                key={item.id}
              >
                <Tooltip placement="right" title={item.title}>
                  <i className="iconfont" style={{ color: item.color }} dangerouslySetInnerHTML={{__html: item.icon}} />
                </Tooltip>
              </div>
            ))}
          </div>
        }
      </div>
      <Canvas 
        onClear={(clearCanvas, undo, redo, setCanvasChangedFn) => {
          clearCanvasRef.current = clearCanvas
          undoRef.current = undo
          redoRef.current = redo
          // 将setCanvasChanged传递给Canvas组件
          setCanvasChangedFn.current = setCanvasChanged
        }} 
        onCanvasRef={(canvas) => {
          canvasRef.current = canvas
        }}
        className="canvas-container" 
        activePenId={activePenId}
        penColor={penColor}
        selectedShape={selectedShape}
        selectedLine={selectedLine}
        selectedText={selectedText}
        drawMode={drawMode}
      />
      {/* 左侧形状栏 */}
      {drawMode === 'shape' && 
        <Shape 
          className="shape"
          onShapeSelect={handleShapeSelect}
          selectedShape={selectedShape}
        />
      }
      {/* 左侧连接线栏 */}
      {drawMode === 'line' && 
        <Line 
          className="line"
          onLineSelect={handleLineSelect}
          selectedLine={selectedLine}
        />
      }
      {/* 底部画笔栏 */}
      {drawMode === 'pen' && 
        <Pens 
          className="pens"
          activePenId={activePenId}
          onChangeActivePenId={setActivePenId}
          penColor={penColor}
          onChangePenColor={setPenColor}
        />
      }
      {/* 左侧文本框栏 */}
      {drawMode === 'text' && 
        <Text 
          className="text"
          onTextSelect={handleTextSelect}
          selectedText={selectedText}
          drawMode={drawMode}
        />
      }
      {/* 画布效果 */}
      {/* <div className="canvas-wrapper">
        <svg width="100%" height="100%">
          <pattern id="dotGrid" x="0" y="0" width="30" height="30" patternUnits="userSpaceOnUse">
              <circle cx="10" cy="10" r="1" fill="#ccc"/>
          </pattern>
          <rect x="0" y="0" width="100%" height="100%" fill="url(#dotGrid)" />
        </svg>
      </div> */}
    </div>
  )
}

export default Board